package cc.ryanc.halo.model.vo;

import cc.ryanc.halo.model.domain.Post;
import cc.ryanc.halo.model.domain.User;
import cc.ryanc.halo.repository.PostRepository;
import com.alibaba.fastjson.JSON;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.PageModelPipeline;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Component("Postpipeline")
public class Postpipeline implements PageModelPipeline<PostPage> {
    Logger logger = LoggerFactory.getLogger(Postpipeline.class);

    private List<Post> posts = new ArrayList<>();

    @Override
    public void process(PostPage postPage, Task task) {
        //持久化这些数据到数据库 post
        Post post = new Post();
        String postTitle = postPage.getPostTitle();
        if (StringUtils.isNotEmpty(postTitle)) {
            String[] split1 = postTitle.split("<title>");
            String[] split2 = split1[1].toString().split("</title>");
            String[] split = split2[0].toString().split("开源中国");
            StringBuilder sb = new StringBuilder();
            if (!CollectionUtils.sizeIsEmpty(split)) {
                for (String s : split) {
                    sb.append(s);
                }
            }
            post.setPostTitle(sb.toString());
            post.setPostSummary(sb.toString());
        }
        post.setPostContent(postPage.getPostContent());
        User user = new User();
        user.setUserId(new Long(1));
        post.setUser(user);
        post.setPostDate(new Date());
        post.setAllowComment(1);
        post.setPostUrl(cn.hutool.core.lang.UUID.randomUUID().toString());
        logger.info("==post:{}==" + JSON.toJSONString(post));
       // postRepository.save(post);
        posts.add(post);
    }

    public List<Post> getPosts() {
        return posts;
    }
}
